<?php
namespace app\sub\controller;

use MongoDB\BSON\ObjectId;
use think\facade\Config;
use think\Db;

class User extends \Common {

    # 获取送、买用户
    public function GetUsers(){
        (new \app\super\controller\User())->GetUsersBySub();
    }

    # 提现
    public function WithDraw(){
        if(isset($_POST["id"]) && isset($_POST["remark"])){
            $ubc_id = $_POST["id"];
            $remark = $_POST["remark"];
            $info = Db::name("user_buy_company")->where("ubc_id", $ubc_id)->find();
            $uid = $info["ub_id"]; $aid = $info["aid"]; $money = ["money"];
            $update = [
                "money" => 0,
                "remark" => $remark,
                "pay_state" => 0
            ];
            Db::name("user_buy_company")->where("ubc_id", $ubc_id)->update($update);
            # 提现记录
            $this->RecordMoney($uid, $aid, $money, 0, $remark, 2);
            Code(200, "提现完成");
        }else{
            Code(403, "服务器错误，请稍后再试");
        }
    }

    # 识别身份证号
    public function OcrByIdCard(){
        if(isset($_FILES["file"])){
            include "./extend/aip/AipOcr.php";
            $client = new \AipOcr(Config::get("app.APP_ID"), Config::get("app.API_KEY"), Config::get("app.SECRET_KEY"));

            $saveimage = UploadFile($_FILES["file"], time(), "./static/upload/people/idcardsave/");

            $url = Config::get("app.ip")."static/upload/people/idcardsave/{$saveimage}";
            $ch = curl_init();
            $timeout = 5;
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
            $image = curl_exec($ch);
            curl_close($ch);

            $idCardSide = "front";
            $options = array();
            $options["detect_direction"] = "true";
            $options["detect_risk"] = "false";

            $info = $client->idcard($image, $idCardSide, $options);

            if(isset($info["words_result"]) && isset($info["words_result"]["公民身份号码"]) && isset($info["words_result"]["姓名"]) && isset($info["words_result"]["公民身份号码"]["words"]) && isset($info["words_result"]["姓名"]["words"]) && $info["words_result"]["姓名"]["words"] != "" && $info["words_result"]["公民身份号码"]["words"] != ""){
                unlink("./static/upload/people/idcardsave/$saveimage");
                $array = [
                    "name" => $info["words_result"]["姓名"]["words"],
                    "idcard" => $info["words_result"]["公民身份号码"]["words"]
                ];
                Code(200, false, $array);
            }else{
                Code(403, "未识别到身份证号，请上传清晰图片。");
            }
        }else{
            Code(403, "服务器错误，请稍后再试");
        }
    }

    # 根绝条件搜索
    public function GetUserByField(){
        $aid = $this->token["id"];
        if(isset($_GET["key"]) && isset($_GET["value"]) && isset($_GET["type"])){
            if($_GET["type"] === "send"){
                if(isset($_GET["value"]) && $_GET["value"] != ""){

                }else{

                }
            }else if($_GET["type"] === "buy"){

            }
        }else{
            Code(403, "服务器错误，请稍后再试");
        }
    }

    # 绑定号码
    public function BindKey(){
        $aid = isset($this->token["pid"]) ? $this->token["pid"] : $this->token["id"];
        if(isset($_POST["id"]) && isset($_POST["subid"]) && isset($_POST["num"]) && isset($_POST["key"])){
            $ub_id = $_POST["id"]; $number = $_POST["num"]; $key = $_POST["key"];
            if(!is_numeric($ub_id)){
                $str = explode("-", $ub_id);
                $ubc_id = $this->AddUserToCom($str[1], $aid);
                if(!is_numeric($ubc_id)){
                    Code(403, "服务器错误，请稍后再试");
                }
                $ub_id = $str[1];
            }
            $check = Db::name("num")->where(function ($query) use ($aid, $ub_id){
                $query->where("aid", $aid)->where("ub_id", $ub_id);
            })->whereOr(function ($query) use ($number, $aid){
                $query->where("aid", $aid)->where("number", $number)->where("ub_id != 0");
            })->whereOr(function ($query) use ($number, $aid){
                $query->where("aid", $aid)->where("number", $number);
            })->order("ub_id desc")->find();
            if(!empty($check)){
                if($check["ub_id"] != 0){
                    if($check["ub_id"] != $ub_id){
                        Code(403, "该号码已经被其它账户绑定, 请核对");
                    }else{
                        Code(403, "该账户已经绑定号码牌，请勿重新绑定");
                    }
                }else{
                    if($check["password"] === $key){
                        $update = [
                            "ub_id" => $ub_id
                        ];
                        Db::name("num")->where("nid", $check["nid"])->update($update);
                        Code(200, "绑定号牌成功");
                    }else{
                        Code(403, "秘钥密码错误");
                    }
                }
            }else{
                Code(403, "号码或者用户信息不存在, 请稍后再试");
            }
        }else{
            Code(403, "服务器错误，请稍后再试");
        }
    }

    # 编辑购买人
    public function UpdateUser(){
        (new \app\super\controller\User())->UpdateUser();
    }

    # 设置保证金
    public function SetMoney(){
        $aid = isset($this->token["pid"]) ? $this->token["pid"] : $this->token["id"];
        if(isset($_POST["money"]) && isset($_POST["id"]) && isset($_POST["remark"])){
            $money = $_POST["money"]; $ubc_id = $_POST["id"]; $remark = $_POST["remark"];
            if(!is_numeric($ubc_id)){
                $str = explode("-", $ubc_id);
                $ubc_id = $this->AddUserToCom($str[1], $aid);
                if(!is_numeric($ubc_id)){
                    Code(403, "服务器错误，请稍后再试");
                }
            }
            $check  = Db::name("user_buy_company")->where("ubc_id", $ubc_id)->find();
            if(!empty($check)){
                $before = $check["money"];
                if($check["pay_state"] == 0){
                    $update = [
                        "pay_state" => $before == $money ? 0 : 1,
                        "money" => $money,
                        "remark" => $remark
                    ];
                    $state = 1;
                }else{
                    $update = [
                        "money" => $money,
                        "remark" => $remark
                    ];
                    $state = -1;
                }
                Db::name("user_buy_company")->where("ubc_id", $ubc_id)->update($update);
                if($before != $money){
                    $this->RecordMoney($check["ub_id"], $this->token["id"], $before, $money, $remark, $state);
                }
                Code(200, "修改成功");
            }else{
                Code(403, "服务器错误，请稍后再试");
            }
        }else{
            Code(403, "服务器错误，请稍后再试");
        }
    }

    # 修改备注
    public function SetRemark(){
        (new \app\super\controller\User())->SetRemark();
    }

    # 获取所有送拍用户
    public function GetAllSendUsers(){
        $aid = isset($this->token["pid"]) ? $this->token["pid"] : $this->token["id"];
        $arr = Db::name("user_send")->field("us_id, name")->select();
        $data = [];
        if(!empty($arr)){
            foreach ($arr as $item) {
                $data[] = [
                    "id" => $item["us_id"],
                    "name" => $item["name"]
                ];
            }
        }
        Code(200, false, $data);
    }

    # 设置VIP
    public function SetVipState(){
        (new \app\super\controller\User())->SetVipState();
    }

    # 获取全部用户
    public function GetAllUsers(){
        $aid = isset($this->token["pid"]) ? $this->token["pid"] : $this->token["id"];
        $buy = []; $send = [];

        $buypeo = Db::name("user_buy_company")
            ->alias("a")
            ->join("c_user_buy b", "a.ub_id = b.ub_id")
            ->where("a.aid", $aid)
            ->select();
        if(!empty($buypeo)){
            foreach ($buypeo as $value){
                $num = Db::name("num")->where("aid", $aid)->where("ub_id", $value["ub_id"])->find();
                if(!empty($num)){
                    $buy[] = [
                        "id" => (int)$value["ub_id"],
                        "address" => $value["address"],
                        "bankcard" => $value["bankcard"],
                        "bankname" => $value["bankname"],
                        "fee_rate" => $value["fee_rate"] * 10000 / 1000000,
                        "label" => $num["number"]."-".$value["name"]."-".$value["tel1"],
                        "name" => $value["name"],
                    ];
                }
            }
        }

        $buycom = Db::name("user_proxy_company")
            ->alias("a")
            ->join("c_user_proxy b", "a.up_id = b.up_id")
            ->where("a.aid", $aid)
            ->select();
        if(!empty($buycom)){
            foreach ($buycom as $value){
                $buy[] = [
                    "id" => "Co-".$value["up_id"],
                    "address" => $value["address"],
                    "bankcard" => $value["bankcard"],
                    "bankname" => $value["bankname"],
                    "fee_rate" => $value["fee_rate"] * 10000 / 1000000,
                    "label" => "Co"."-".$value["name"]."-".$value["tel"],
                    "name" => $value["name"],
                ];
            }
        }


        $sendpeo = Db::name("user_send_company")
            ->alias("a")
            ->join("c_user_send b", "a.us_id = b.us_id")
            ->where("a.aid", $aid)
            ->select();
        if(!empty($sendpeo)){
            foreach ($sendpeo as $value){
                $send[] = [
                    "id" => (int)$value["us_id"],
                    "address" => $value["address"],
                    "bankcard" => $value["bankcard"],
                    "bankname" => $value["bankname"],
                    "fee_rate" => $value["fee_rate"] * 10000 / 1000000,
                    "label" => $value["name"]."-".$value["tel1"],
                    "name" => $value["name"],
                    "catafee" => $value["catafee"]
                ];
            }
        }

        Code(200, false, ["buy" => $buy, "send" => $send]);
    }

    # 新增用户到公司旗下
    private function AddUserToCom($uid, $aid, $type = "buy"){
        if($type === "buy"){
            $check = Db::name("user_buy_company")->where("ub_id", $uid)->where("aid", $aid)->find();
            if(empty($check)){
                $insert = [
                    "ub_id" => $uid,
                    "aid" => $aid,
                    "reg_time" => time(),
                ];
                return Db::name("user_buy_company")->insertGetId($insert);
            }else{
                return $check["ubc_id"];
            }
        }else{
            $check = Db::name("user_send_company")->where("us_id", $uid)->where("aid", $aid)->find();
            if(empty($check)){
                $insert = [
                    "us_id" => $uid,
                    "aid" => $aid,
                    "reg_time" => time(),
                ];
                return Db::name("user_send_company")->insertGetId($insert);
            }else{
                return $check["usc_id"];
            }
        }
    }

}